package com.liang.service.impl;

import com.liang.entity.CNews;
import com.liang.mapper.CNewsMapper;
import com.liang.service.CNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李昂
 * @since 2021-01-14
 */
@Service
@CacheConfig(cacheNames = "CNewsMapper")
public class CNewsServiceImpl extends ServiceImpl<CNewsMapper, CNews> implements CNewsService {

    @Override
    @CacheEvict(value = "news", allEntries = true)
    public boolean publicNews(CNews news) {
        return this.save(news);
    }

    @Override
    @Cacheable(value = "news")
    public List<CNews> getNewsList() {
        return this.baseMapper.getNewsList();
    }

    @Override
    @Cacheable(key = "#id")
    public String getContainer(int id) {
        return this.baseMapper.getContainer(id);
    }

    @Override
    @CacheEvict(value = "news", allEntries = true)
    public boolean deleteNews(int id) {
        return this.removeById(id);
    }

    /**
     * 点击查看的人数
     * 这里使用乐观锁机制，防止在大吞吐量时数据更新失败.
     * <p>
     * 1.查出跟新之前的 looks
     * 2.在更新时进行looks比对 看是否一样，一样就更新成功
     * 3.这样做可以确保looks查看总数准确无误
     */
    @Override
    @Transactional()
    @CacheEvict(value = "news", allEntries = true)
    public boolean updateLook(int id) {
        int look = this.baseMapper.getLooks(id);
        return this.baseMapper.updateLook(id, look);
    }
}
